package com.itconnect.inc.adapters;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TimeZone;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.PopupMenu.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.itconnect.inc.entertainment.R;
import com.example.ytc.clazz.ActionButonEvent;
import com.example.ytc.clazz.Video;
import com.example.ytc.tools.FavoritDAO;
import com.example.ytc.tools.Utils;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

public class YouTubeAdapter extends BaseAdapter {

	Context mContext;
	Intent intent;
	LayoutInflater mInflater;
	ArrayList<Video> videolist;
	

	public YouTubeAdapter(Context context, ArrayList<Video> v) {
		mContext = context;
		videolist = v;
		mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public void removeDuplicated() {
		HashSet hs = new HashSet();
		hs.addAll(videolist);
		videolist.clear();
		videolist.addAll(hs);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return videolist.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View arg1, ViewGroup arg2) {
		final ViewHolder vh;
		if (arg1 == null) {
			arg1 = mInflater.inflate(R.layout.video, null);
			vh = new ViewHolder();
			vh.tv = (TextView) arg1.findViewById(R.id.tvv);
			vh.description = (TextView) arg1
					.findViewById(R.id.show_description);
			vh.iv = (ImageView) arg1.findViewById(R.id.ivv);
			vh.duration = (TextView) arg1.findViewById(R.id.duration);
			vh.options = (ImageView) arg1.findViewById(R.id.options);
			vh.options.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					showPopup(v,vh.selectedvideo);
				}
			});

			arg1.setTag(vh);
		} else {
			vh = (ViewHolder) arg1.getTag();
		}
		vh.tv.setText(videolist.get(position).getTitel());
		vh.description.setText(videolist.get(position).getDescription());
		vh.selectedvideo = videolist.get(position);
		vh.duration.setText(ConvertSecondToHHMMString(videolist.get(position)
				.getDuration()));
		UrlImageViewHelper.setUrlDrawable(vh.iv, videolist.get(position)
				.getImage_url());
		
		return arg1;
	}



	private void showPopup(final View v,final Video selected_video) {
		PopupMenu popup = new PopupMenu(v.getContext(), v);
		MenuInflater inflater = popup.getMenuInflater();
		inflater.inflate(R.menu.video_menu, popup.getMenu());
		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				ActionButonEvent action=new ActionButonEvent(mContext.getApplicationContext(),selected_video); 
				int id = item.getItemId();
				switch (item.getItemId()) {
				case R.id.share:
					action.share();
					break;
				case R.id.addfavorite:
					action.add_to_favorits();
					break;
				case R.id.removefavorite:
					action.remove_favorits();
					break;
				default:
					
					showPopup(v,selected_video);
				}

				return true;

			}
		});
		try {
			Menu menu=popup.getMenu();
			if (Utils.contains(FavoritDAO.get(v.getContext()),
					selected_video.getIvide())) {
				menu.findItem(R.id.removefavorite).setVisible(true);
				menu.findItem(R.id.addfavorite).setVisible(false);
			
			} else {
				menu.findItem(R.id.removefavorite).setVisible(false);
				menu.findItem(R.id.addfavorite).setVisible(true);
			}
			try {
			    Field[] fields = popup.getClass().getDeclaredFields();
			    for (Field field : fields) {
			        if ("mPopup".equals(field.getName())) {
			            field.setAccessible(true);
			            Object menuPopupHelper = field.get(popup);
			            Class<?> classPopupHelper = Class.forName(menuPopupHelper
			                    .getClass().getName());
			            Method setForceIcons = classPopupHelper.getMethod(
			                    "setForceShowIcon", boolean.class);
			            setForceIcons.invoke(menuPopupHelper, true);
			            break;
			        }
			    }
			} catch (Exception e) {
			    e.printStackTrace();
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		popup.show();

	}

	private String ConvertSecondToHHMMString(int secondtTime) {
		TimeZone tz = TimeZone.getTimeZone("UTC");
		SimpleDateFormat df = new SimpleDateFormat("mm:ss");
		df.setTimeZone(tz);
		String time = df.format(new Date(secondtTime * 1000L));

		return time;

	}

	static class ViewHolder {
		TextView tv;
		ImageView iv;
		ImageView options;
		TextView description;
		TextView duration;
		Video selectedvideo;
	}
}